import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import http from '@/utils/request'
import type { FormProps } from 'antd'
import { Button, Form, Input, message, Spin } from 'antd'
import useuserInfoStore from '@/store/userInfo'
import './index.scss'

interface FieldType {
  userCode?: string;
  password?: string;
  remember?: string;
}
const Login: React.FC = () => {
  const [loading, setLoading] = useState(false)

  const updateUserInfo = useuserInfoStore((state) => state.updateUserInfo)
  const navigate = useNavigate()

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    setLoading(true)
    http.post('/disp/manage/system/login', {
      ...values,
      platform: 'PC'
    }).then(res => {
      const { token, userVo } = res.data
      localStorage.setItem('token', token)
      updateUserInfo({
        token,
        ...userVo
      })
      navigate('/order/order-list', { replace: true })
    }).catch(err => {
      message.error(err.msg || '请求数据失败')
    }).finally(() => {
      setLoading(false)
    })
  }
  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo)
  }

  // const getUserInfo = () => {
  //   setLoading(true)
  //   http.get('/disp/sys/user/getLoginUserInfo').then((res) => {
  //     const { userVo } = res.data
  //     updateUserInfo({
  //       ...userVo
  //     })
  //     navigate('/home', { replace: true })
  //   }).finally(() => {
  //     setLoading(false)
  //   })
  // }

  useEffect(() => {
    // getUserInfo()
  }, [])
  return (
    <div className="page login flex-row flex-center">
      {loading ? <Spin tip="正在登录中..." fullscreen/> : null}
      <div className="login-container">
        <div className="title">登陆</div>
        <Form
          name="basic"
          style={{ maxWidth: 800 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="账号"
            name="userCode"
            rules={[{ required: true, message: '请输入账户!' }]}
          >
            <Input/>
          </Form.Item>

          <Form.Item<FieldType>
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password/>
          </Form.Item>

          {/* <Form.Item<FieldType> name="remember" valuePropName="checked" label={null}> */}
          {/*   <Checkbox>记住</Checkbox> */}
          {/* </Form.Item> */}

          <Form.Item label={null}>
            <Button style={{ width: '100%' }} type="primary" htmlType="submit">登录</Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login